package huzh.foundation.util;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;

/**
 *<p>title:ClassPathHacker</p>
 *<p>description:</p>
 * @since 2014-6-6
 * @author huzh
 * @version 1.0
 */
public class ClassPathHacker {
    /**parameters*/
    @SuppressWarnings("unchecked")
    private static final Class[] parameters = { URL.class };

    /**hackerPathList*/
    private static ArrayList<String> hackerPathList = new ArrayList<String>();

    /**
     * @return
     */
    public static ArrayList<String> getHackerPathList() {
        return hackerPathList;
    }

    /**
     * @param s
     * @throws IOException
     */
    public static void addFile(String s) throws IOException {
        hackerPathList.add(s);
        File f = new File(s);
        addFile(f);
    }

    /**
     * @param f
     * @throws IOException
     */
    @SuppressWarnings("deprecation")
    private static void addFile(File f) throws IOException {
        addURL(f.toURL());
    }

    /**
     * @param u
     * @throws IOException
     */
    @SuppressWarnings("unchecked")
    private static void addURL(URL u) throws IOException{
        URLClassLoader sysloader = (URLClassLoader)ClassLoader.getSystemClassLoader();
        Class sysclass = URLClassLoader.class;
        try{
            Method method = sysclass.getDeclaredMethod("addURL", parameters);
            method.setAccessible(true);
            method.invoke(sysloader, new Object[] { u });
        } catch (Throwable t) {
            t.printStackTrace();
            throw new IOException("Error, could not add URL to system classloader");
        }
    }
}
